//
//  CarServiceDetailViewController.m
//  JxCarios
//
//  Created by xcq on 15/2/4.
//  Copyright (c) 2015年 xiongchuanqi. All rights reserved.
//

#import "CarServiceDetailViewController.h"

#import "RoadsideAssistanceShopServiceCell.h"
#import "DrawTrailerTableViewCell.h"
#import "ReplaceDriveDetailCallCell.h"
#import "RoadsideAssistanceNightTableCell.h"
#import "LoginViewController.h"
#import "CLUIBaseNavigationController.h"
#import "MyOrderViewController.h"

static NSString *drawStr = @"DrawTrailer";
static NSString *callStr = @"detailcall";
static NSString *checkStr = @"RoadsideAssistanceShopServiceCell";
static NSString *cellNight = @"RoadsideNight";

@interface CarServiceDetailViewController (){
    CGSize tableSize;
}

@end

@implementation CarServiceDetailViewController

- (void)viewDidLoad {
     [super viewDidLoad];
    self.tableView.hidden = YES;
    _currenPage = 2;
    _checkInteger = 0;
    [self initAbout];
    [self netRequst];
}

- (void)netRequst {
    if (!self.carDataSource) {
        self.carDataSource = [CarAroundDataSource dataSourceWithRequestor:self];
    }
    
    self.carDataSource.dic_type = _dic_type;
    self.carDataSource.shopId = _shopId;
    [self.carDataSource carAroundShopDetail:^(id result) {
        _shopDetailDic = [result objectForKey:@"seller"];
        _currenPage = [[result objectForKey:@"totalpages"] integerValue];
         _currenService = [NSArray arrayWithArray:[result customObjectForkey:@"serviceone"]];
        _otherArr = [NSMutableArray arrayWithArray:[result customObjectForkey:@"servicetwo"]];
        [self initDataSource];
    } anfFail:^(id result) {
        
    }];
}

- (void)initDataSource {
    if ([[_shopDetailDic objectForKey:@"IS_PAY"] isEqualToString:@"yes"]) {
        _isPay = YES;
    }else{
        _isPay = NO;
    }
    if (_currenService.count > 0) {
        if (_otherArr.count > 0) {
            _section = 4;
        }else{
            _section = 3;
        }
    }else{
        _section = 2;
    }
     _callArray = [NSMutableArray arrayWithArray:[[_shopDetailDic objectForKey:@"TEL"] componentsSeparatedByString:@","]];
    int i = 0 ;
    BOOL replace = NO;
    for (int a = 0 ;a < _callArray.count; a ++) {
        NSString *str = [_callArray objectAtIndex:a];
        if ([str isEqualToString:@"null"]) {
            i = a;
            replace = YES;
        }
    }
    if (replace) {
        [_callArray  removeObjectAtIndex:i];
    }
    self.tableView.hidden = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource  = self;
    [self.tableView reloadData];
}

- (void)initAbout {
    self.title = @"商家详情";
    [self showNavBarWithRightTitle:nil andRightAction:nil andLeftAction:nil andCustom:NO];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStyleGrouped];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.tableView];
    [self.view bringSubviewToFront:_checkView];
    REGISTCELL(@"RoadsideAssistanceShopServiceCell", checkStr);
    REGISTCELL(@"DrawTrailerTableViewCell", drawStr);
    REGISTCELL(@"ReplaceDriveDetailCallCell", callStr);
    REGISTCELL(@"RoadsideAssistanceNightTableCell", cellNight);
    _checkView.backgroundColor = UICOLOR_MAKE_RGB(235, 235, 241);
    [self.tableView addFooterWithTarget:self action:@selector(footerRerfesh)];
}

- (void)footerRerfesh{
    if (_countPage <= _currenPage) {
        [self.view.window makeToast:@"没有更多数据了哦"];
        [self.tableView footerEndRefreshing];
        return;
    }
    _currenPage ++;
    [self.carDataSource carRefrsh:^(id result) {
        [_otherArr addObjectsFromArray:[result objectForKey:@"servicetwo"]];
        NSIndexSet *set = [[NSIndexSet alloc] initWithIndex:3];
        [self.tableView reloadSections:set  withRowAnimation:UITableViewRowAnimationLeft];
        [self.tableView footerEndRefreshing];
    } anfFail:^(id result) {
        _currenPage --;
        [self.tableView footerEndRefreshing];
    }];
    
}

#pragma mark - tableView Delegate & DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _section;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
        {
            return 1;
            break;
        }
        case 1:{
            return [_callArray count] <= 0 ? 0 : _callArray.count;
            break;
        }
        case 2:{
            return [_currenService count] <= 0 ? 0 : [_currenService count];
            break;
        }
        case 3:{
            return [_otherArr count] <= 0 ? 0 : [_otherArr count];
            break;
        }
            
        default:
            break;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
        {
            DrawTrailerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:drawStr forIndexPath:indexPath];
            [cell.praiseView removeGestureRecognizer:cell.tap];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (_isPay) {
                cell.superType = @"cell";
            }else{
                cell.superType = @"noPay";
            }
             cell.info = _shopDetailDic;
            if ([cell.distanceLabel.text isEqualToString:@"0.0km"]) {
                 cell.distanceLabel.text = [[NSString stringWithFormat:@"%.1f",[_distance floatValue] / 1000] stringByAppendingString:@"km"];
            }
            return cell;
            break;
        }
            
        case 1:
        {
            ReplaceDriveDetailCallCell *call = [tableView dequeueReusableCellWithIdentifier:callStr forIndexPath:indexPath];
            call.count = indexPath.row;
            call.phone.text = [_callArray objectAtIndex:indexPath.row];
            call.selectionStyle = UITableViewCellSelectionStyleNone;

            return call;
            break;
        }
        case 2:
        {
            RoadsideAssistanceShopServiceCell *shopService = [tableView dequeueReusableCellWithIdentifier:checkStr forIndexPath:indexPath];
            shopService.delegate = self;
            shopService.info = [_currenService objectAtIndex:indexPath.row];
            shopService.selectionStyle = UITableViewCellSelectionStyleNone;
            return shopService;
            break;
        }
        case 3:
        {
            if (_isPay) {
                RoadsideAssistanceShopServiceCell *shopService = [tableView dequeueReusableCellWithIdentifier:checkStr forIndexPath:indexPath];
                shopService.delegate = self;
                shopService.info = [_otherArr objectAtIndex:indexPath.row];
                shopService.selectionStyle = UITableViewCellSelectionStyleNone;
                return shopService;
            }else{
                NSString *str = @"￥";

                RoadsideAssistanceNightTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellNight forIndexPath:indexPath];
                cell.shopName.textColor  =[UIColor blackColor];
                cell.shopPrice.textColor = BTN_COLOR;
                cell.shopPrice.text = [str stringByAppendingString:[[_otherArr objectAtIndex:indexPath.row] customObjectForkey:@"CHEAP_PRICE"]];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.shopName.text = [[_otherArr objectAtIndex:indexPath.row] customObjectForkey:@"GOOD_NAME"];
                return cell;
            }
         
            break;
        }
       
        
    }
    return nil;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
        {
            return 88;
            break;
        }
        case 1:
        {
            return 44;
            break;
        }
        case 2:
        {
            return 44;
            break;
        }
        case 3:
        {
            if (_isPay) {
                return 44;
            }else {
                return 40;
            }
            break;
        }
        default:
            break;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0){
        return 0;
    }else if (section == 2){
        return 20;
    }
    return 30;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        _detailSize = [Common sizeWithContent:[_shopDetailDic customObjectForkey:@"INTRODUCE"] AndFont:[UIFont systemFontOfSize:13.0f] andSize:[RextExtends getScreenFrame].size andLineBreak:UILineBreakModeWordWrap];
        _detailSize.height += 15;
        return _detailSize.height + 40;
    }else{
        return 10;
    }

}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0) {
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, _detailSize.height + 40)];
        view.backgroundColor = [UIColor whiteColor];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(2, 2, [RextExtends getScreenFrame].size.width, _detailSize.height)];
        label.backgroundColor = [UIColor redColor];
        if (_shopDetailDic) {
            label.text = [@"      " stringByAppendingString:[_shopDetailDic customObjectForkey:@"INTRODUCE"]] ;
        }
        label.font = [UIFont systemFontOfSize:13.0f];
        //清空背景颜色
        label.backgroundColor = [UIColor clearColor];
        //设置字体颜色为白色
        label.textColor = [UIColor blackColor];
        //文字居中显示
        label.textAlignment = NSTextAlignmentLeft;
        //自动折行设置
        label.lineBreakMode = UILineBreakModeWordWrap;
        label.numberOfLines = 0;
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, label.frame.origin.y + _detailSize.height, [RextExtends getScreenFrame].size.width, 1)];
        lineView.backgroundColor = UICOLOR_MAKE_RGB(239, 238, 244);
        UILabel *addressLabel = nil;
        CGSize size = [Common sizeWithContent:[_shopDetailDic customObjectForkey:@"SHOP_ADDR"] AndFont:[UIFont systemFontOfSize:13.0f] andSize:CGSizeMake(([RextExtends getScreenFrame].size.width * 0.8 ) - 10 , 40) andLineBreak:UILineBreakModeWordWrap];
        if(size.height > (40 / 2) ){
            addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, lineView.frame.origin.y + 1 + 2, size.width, size.height + 5)];
        }else{
            addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, lineView.frame.origin.y + 1 + 10, size.width, size.height + 5)];
        }
        addressLabel.lineBreakMode = UILineBreakModeWordWrap;
        addressLabel.numberOfLines = 0;
        CGFloat distanceW = [RextExtends getScreenFrame].size.width ;
        UILabel *distanceLabel = [[UILabel alloc] initWithFrame:CGRectMake((distanceW * 0.8) + 20, lineView.frame.origin.y + 1 + 10, distanceW - 15, 20)];
        
        distanceLabel.font = [UIFont systemFontOfSize:11.0f];
        distanceLabel.text = [[NSString stringWithFormat:@"%.1f",[_distance doubleValue] / 1000] stringByAppendingString:@"Km"];
        distanceLabel.textColor = [UIColor grayColor];
        
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(distanceW * 0.8, distanceLabel.frame.origin.y + 2, 15, 15)];
        [imageV setImage:[UIImage imageNamed:@"dingwei"]];
        
        addressLabel.text = [_shopDetailDic customObjectForkey:@"SHOP_ADDR"];
        addressLabel.textAlignment = NSTextAlignmentLeft;
        addressLabel.font = [UIFont systemFontOfSize:13.0f];
        [view addSubview:distanceLabel];
        [view addSubview:imageV];
        [view addSubview:addressLabel];
        [view addSubview:lineView];
        [view addSubview:label];
        return view;
    }else{
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2) {
        RoadsideAssistanceShopServiceCell *service = (RoadsideAssistanceShopServiceCell *)[tableView cellForRowAtIndexPath:indexPath];
        [service checkAction:service.checkBtn];
    }else if (indexPath.section == 3){
        if (_isPay) {
            RoadsideAssistanceShopServiceCell *service = (RoadsideAssistanceShopServiceCell *)[tableView cellForRowAtIndexPath:indexPath];
            [service checkAction:service.checkBtn];
        }
    }
}


- (void)checkCallBack:(UITableViewCell *)cell andSeleted:(BOOL)seleted{
    if (!_seletedShop) {
        _seletedShop = [NSMutableArray new];
    }
    RoadsideAssistanceShopServiceCell *_cell = (RoadsideAssistanceShopServiceCell*)cell;
    NSLog(@"cell.info : %@" ,_cell.info);
    if (seleted) {
        [_seletedShop addObject:_cell.info];
        [self priceSum:YES price:[_cell.info customObjectForkey:@"CHEAP_PRICE"]];
        _checkView.hidden = NO;
        tableSize = _tableView.contentSize;
        _tableView.contentSize = CGSizeMake(tableSize.width, tableSize.height + 62);
        
    }else{
        [_seletedShop removeObject:_cell.info];
        [self priceSum:NO price:[_cell.info customObjectForkey:@"CHEAP_PRICE"]];
        if (_seletedShop.count == 0) {
            _checkView.hidden = YES;
            _checkInteger = 0;
            _tableView.contentSize = tableSize;
        }
    }
}

- (void)priceSum:(BOOL)bol price:(NSString *)price{
    if (bol) { //+
        _checkInteger += [price doubleValue];
    }else{ //--
        _checkInteger -= [price doubleValue];

    }
    _checkPrice.text = [RMB stringByAppendingString:[NSString stringWithFormat:@"%.2f",_checkInteger]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (IBAction)submitAction:(id)sender {
    if(![Common currenLoginStatus]){
        LoginViewController *login = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginView"];
        CLUIBaseNavigationController *base = [[CLUIBaseNavigationController alloc] initWithRootViewController:login];
        login.hidesBottomBarWhenPushed = YES;
        [self presentViewController:base animated:YES completion:^{
            
        }];
    }else {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TipsGoOrder:) name:@"payTips" object:nil];
        PayViewController *pay = [[PayViewController alloc] initWithNibName:@"PayViewController" bundle:nil];
        pay.buyShopArr = [_seletedShop copy];
        pay.countPrice = _checkInteger;
        [self.navigationController pushViewController:pay animated:YES];
    }
}

- (void)TipsGoOrder:(NSNotification *)notification {
    UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"订单成功" message:@"您已经完成了订单!\n可前往我的订单中查看订单最新状态" delegate:self cancelButtonTitle:@"去看看" otherButtonTitles:@"下次再看", nil];
    view.tag = 500;
    [view show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if(buttonIndex == 0){
        MyOrderViewController *myorder = (MyOrderViewController *)[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"myOrder"];
        [self.navigationController pushViewController:myorder animated:YES];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}
@end
